<?php
function show_message($target_url, $content = "操作成功", $delay_time = 3)
{
	$CI = &get_instance();
	$data = array(
		'target_url' => $target_url,
		'content' => $content,
		'delay_time' => $delay_time
	);
	$CI->smarty->display('show_message.html', $data);
}

function show_error_message($target_url, $content = "操作成功", $delay_time = 3)
{
	$CI = &get_instance();
	$data = array(
		'target_url' => $target_url,
		'content' => $content,
		'delay_time' => $delay_time
	);
	$CI->smarty->display('show_error_message.html', $data);
}

function get_field_by_where($table, $fileds = '*', $where = '1=1')
{
	$CI =& get_instance();
	$sql = "SELECT $fileds FROM {$CI->db->dbprefix}{$table} WHERE $where";
	$result = $CI->db->query($sql)->row_array();
	return $result;
}

function get_menu_title_by_menu_url($menu_url)
{
	$CI =& get_instance();
	$CI->load->model("privileges");
	$info = $CI->privileges->get_field_by_where("menu_title", "menu_url='{$menu_url}'");
	return isset($info['menu_title']) ? $info['menu_title'] : '';
}

function create_uuid($prefix = "")
{    //可以指定前缀
	$str = md5(uniqid(mt_rand(), true));
	$uuid = substr($str, 0, 8) . '-';
	$uuid .= substr($str, 8, 4) . '-';
	$uuid .= substr($str, 12, 4) . '-';
	$uuid .= substr($str, 16, 4) . '-';
	$uuid .= substr($str, 20, 12);
	return $prefix . $uuid;
}

function get_qiniu_token($type = 'VIDEO', $video_name = '') {
    require_once ("third_party/qiniu/lib/rs.php");
    if($video_name == '') $video_name = time() . '.mp4';
    $CI =& get_instance();
    $CI->config->load('qiniu_config');
    $qiniu_config  = $CI->config->item('THINK_SDK_QINIU');       
    Qiniu_SetKeys ( $qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET'] );
    $putPolicy = new Qiniu_RS_PutPolicy ( $qiniu_config[$type]['UPLOAD_DOMAIN'] );
    /*if($video_name != ''){
        $putPolicy->SaveKey = $video_name;
    }*/
    if($type == 'VIDEO'){
        // $putPolicy->PersistentOps = 'vframe/jpg/offset/5|saveas/' . base64_encode($qiniu_config['VIMG']['UPLOAD_DOMAIN'] . ':' . md5(rand(100001, 100000009) . $video_name));
        $putPolicy->PersistentOps = 'avthumb/mp4/r/24/vcodec/libx264';
        // $putPolicy->Transform = 'avthumb/mp4/vcodec/copy/acodec/copy';
        $putPolicy->PersistentPipeline = "dax-moov";
    }
    $upToken = $putPolicy->Token ( null );
    return $upToken;
}

function delete_qiniu_data($key, $type = "VIDEO")
{
	require_once("third_party/qiniu/lib/rs.php");
	$CI =& get_instance();
	$CI->config->load('qiniu_config');
	$qiniu_config = $CI->config->item('THINK_SDK_QINIU');
	Qiniu_SetKeys($qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET']);
	$client = new Qiniu_MacHttpClient(null);
	$err = Qiniu_RS_Delete($client, $qiniu_config[$type]['UPLOAD_DOMAIN'], $key);
	/*if ($err !== null) {
		var_dump($err);
	} else {
		echo "Success!";
	}*/
}

function GetIpLookup($ip = '')
{
	//    if(empty($ip)){
	//        $ip = GetIp();
	//    }
	$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
	if (empty($res)) {
		return false;
	}
	$jsonMatches = array();
	preg_match('#\{.+?\}#', $res, $jsonMatches);
	if (!isset($jsonMatches[0])) {
		return false;
	}
	$json = json_decode($jsonMatches[0], true);
	if (isset($json['ret']) && $json['ret'] == 1) {
		$json['ip'] = $ip;
		unset($json['ret']);
	} else {
		return false;
	}
	return $json;
}

function is_ajax_request()
{
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		return true;
	} else {
		return false;
	}
}

function curlRequest($url, $args = '', $method = 'POST', $json = false)
{
	$url = $url;
	$method = $method;
	$data = $args;
	if ($json) {
		$headers = array(
			'Accept: application/json',
			'Content-Type: application/json',
		);
		$data = json_encode($args);
	}
	$url_arr = parse_url($url);

	$handle = curl_init();
	curl_setopt($handle, CURLOPT_URL, $url);
	if ($json) curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
	if ($url_arr['scheme'] == 'https') {
		curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
	}
	curl_setopt($handle, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	switch (strtoupper($method)) {
		case 'GET':
			break;
		case 'POST':
			curl_setopt($handle, CURLOPT_POST, 1);
			curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
			break;
		case 'PUT':
			curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
			curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
			break;
		case 'DELETE':
			curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
			curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
			break;
	}
	ob_start();
	$response = curl_exec($handle);
	$error = curl_error($handle);
	$info = curl_getinfo($handle);
	if ($error) {
		var_dump($error);
	}
	ob_end_clean();
	curl_close($handle);
	if ($error) {
		var_dump($error);
	}
	/*print_r($response);
	print_r($info);*/
	// file_put_contents('uploads/'.time().'-'.$data['admin_id'].'.txt', json_encode($data) . json_encode($info));
	return $response;
}

function get_qiniu_url($url = '', $type = 'VIMG')
{
	if (strstr($url, 'http://') || $url == '') {
		return $url;
	} else {
		$CI =& get_instance();
		$CI->config->load('qiniu_config');
		$qiniu_config = $CI->config->item('THINK_SDK_QINIU');
		$url = 'http://' . $qiniu_config[$type]['DOMAIN_PREFIX'] . '.' . $qiniu_config[$type]['DOMAIN'] . '/' . $url;
		return $url;
	}
}

function getRandChar($length)
{
	$str = null;
	$strPol = "0123456789";
	$max = strlen($strPol) - 1;

	for ($i = 0; $i < $length; $i++) {
		$str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}

	return $str;
}

/**
 * 发送验证码短信
 * @param  [type] $phone   [description]
 * @param  [type] $content [description]
 * @return [type]          [description]
 */
function send_verify_code_msg($phone, $content)
{
	$SERVER_URL = "https://api.netease.im/sms/sendtemplate.action";
	$APP_SECRET = "9e9bcd454ade";
	$APP_KEY = "226dea55d918dc41248e9a868cd14e12";
	$template_id = "3058376";
	$NONCE = "ABC123456";

	$curTime = time();
	$checkSum = sha1($APP_SECRET . $NONCE . $curTime);
	// print_r($checkSum);

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $SERVER_URL);

	$header[0] = "Content-Type:application/x-www-form-urlencoded;charset=utf-8";
	$header[] = "AppKey:" . $APP_KEY;
	$header[] = "CurTime:" . $curTime;
	$header[] = "CheckSum:" . $checkSum;
	$header[] = "Nonce:" . $NONCE;
	// echo sha1($str);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, "templateid=" . $template_id . "&mobiles=['" . $phone . "']&params=['" . $content . "']");
	ob_start();
	curl_exec($curl);
	// $error    = curl_error($curl);
	// $info    = curl_getinfo($curl);
	// echo "{'status':1,'code':'','msg':'".$info."'}";
	//
	$result = ob_get_contents();
	ob_end_clean();
	curl_close($curl);
	return $result;
}


// function send_verify_code_msg($phone, $code){
	
// 	$APP_ID = "cf_dax";
// 	$APP_KEY = "fadd9a1c379c93927ed7f1a2c2f2bebc";

// 	$time=time();
// 	$password=md5($APP_ID.$APP_KEY.$phone.$code.$time);
// 	$content = "欢迎注册德安信教育云平台帐号，验证码为{$code}。";

// 	$URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit&account={$APP_ID}&password={$APP_KEY}&mobile={$phone}&content={$content}&format=json";

	
// 	// print_r($checkSum);

// 	$curl = curl_init();
// 	curl_setopt($curl, CURLOPT_URL, $URL);

// 	// $header[0] = "Content-Type:application/x-www-form-urlencoded;charset=utf-8";
// 	// $header[] = "AppKey:" . $APP_KEY;
// 	// $header[] = "CurTime:" . $curTime;
// 	// $header[] = "CheckSum:" . $checkSum;
// 	// $header[] = "Nonce:" . $NONCE; CURLOPT_POST
// 	// echo sha1($str);
// 	// curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

// 	curl_setopt($curl, CURLOPT_HTTPGET , 1);
// 	// curl_setopt($curl, CURLOPT_POSTFIELDS,);
// 	ob_start();
// 	curl_exec($curl);
// 	// $error    = curl_error($curl);
// 	// $info    = curl_getinfo($curl);
// 	// echo "{'status':1,'code':'','msg':'".$info."'}";
// 	//
// 	$result = ob_get_contents();
// 	ob_end_clean();
// 	curl_close($curl);
// 	return $result;
	
// }

function timediff($begin_time,$end_time){
	if($begin_time < $end_time){
		$starttime = $begin_time;
		$endtime = $end_time;
	}else{
		$starttime = $end_time;
		$endtime = $begin_time;
	}

	//计算天数
	$timediff = $endtime-$starttime;
	$days = intval($timediff/86400);
	//计算小时数
	$remain = $timediff%86400;
	$hours = sprintf('%02s', intval($remain/3600));
	//计算分钟数
	$remain = $remain%3600;
	$mins = sprintf('%02s', intval($remain/60));
	//计算秒数
	$secs = sprintf('%02s', $remain%60);
	$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
	return $res;
}

function reg_wecenter($user_name, $password, $email, $sex = 3){
	$curl_data['user_name']     = $user_name;
    $curl_data['email']     	= $email;
    $curl_data['password']      = $password;
    $curl_data['sex']           = $sex;
    $curl_data['agreement_chk'] = 'agree';
    curlRequest("http://".$_SERVER['HTTP_HOST']."/ask/?/account/ajax/register_process/",$curl_data);
}

function login_wecenter($user_name, $password){
    $curl_data['user_name']     = $user_name;
    $curl_data['password']      = $password;
    $curl_data['_post_type']    = 'ajax';
    $ck = curlRequest("http://".$_SERVER['HTTP_HOST']."/ask/?/account/ajax/th_login_process/",$curl_data);
    $cd_data = explode("cast", strip_tags($ck));
    setcookie(substr($cd_data[0], -4)."_user_login", 'cast'.$cd_data[1], time() + 3600 * 24, '/');
}

/** 
 * 计算几分钟前、几小时前、几天前、几月前、几年前。 
 * $agoTime string Unix时间 
 * @author tangxinzhuan 
 * @version 2016-10-28 
 */  
function time_ago($agoTime)
{
    $agoTime = (int)$agoTime;
    // 计算出当前日期时间到之前的日期时间的毫秒数，以便进行下一步的计算
    $time = time() - $agoTime;
    if ($time >= 31104000) { // N年前
        $num = (int)($time / 31104000);
        return $num.'年前';
    }
    if ($time >= 2592000) { // N月前
        $num = (int)($time / 2592000);
        return $num.'月前';
    }
    if ($time >= 86400) { // N天前
        $num = (int)($time / 86400);
        return $num.'天前';
    }
    if ($time >= 3600) { // N小时前
        $num = (int)($time / 3600);
        return $num.'小时前';
    }
    if ($time > 60) { // N分钟前
        $num = (int)($time / 60);
        return $num.'分钟前';
    }
    return '1分钟前';
}

//批量删除
function delete_data($ids, $table){
    $CI =& get_instance();
    $ids = implode(",",$ids);
    $sql = "DELETE FROM {$CI->db->dbprefix}{$table} WHERE id in($ids)";
    $CI->db->query($sql);
}

function upload_image($file, $path = 'sataic/uploads'){
	
}

function get_topic_subject($topic_subject_id){
	$subject_info = get_field_by_where("tk_accounts_subject", "title", "id='{$topic_subject_id}'");
	echo $subject_info['title'];
}

function create_rand_str($min_length = 1, $max_length = 8, $type = 'all'){
    $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    if($max_length < $min_length) $max_length = $max_length + $min_length;
    $str_length = mt_rand($min_length, $max_length);
    if($type == 'all'){
        $start_rand = 0;
        $end_rand = strlen($string) - 1;
    }elseif($type == 'number'){
        $start_rand = 52;
        $end_rand = strlen($string) - 1;
    }elseif($type == 'abc'){
        $start_rand = 0;
        $end_rand = strlen($string) - 11;
    }else{
        return false;
    }
    $str = '';
    for ($i=0; $i < $str_length; $i++) { 
        $str .= $string[ mt_rand($start_rand, $end_rand) ];
    }
    return $str;
}

function getDistance($lat1, $lng1, $lat2, $lng2){   
	$earthRadius = 6367000; //approximate radius of earth in meters   
	$lat1 = ($lat1 * pi() ) / 180;   
	$lng1 = ($lng1 * pi() ) / 180;   
	$lat2 = ($lat2 * pi() ) / 180;   
	$lng2 = ($lng2 * pi() ) / 180;   
	$calcLongitude = $lng2 - $lng1;   
	$calcLatitude = $lat2 - $lat1;   
	$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);   
	$stepTwo = 2 * asin(min(1, sqrt($stepOne)));   
	$calculatedDistance = $earthRadius * $stepTwo;   
	return round($calculatedDistance);   
}

function changeTimeType($seconds){
    if ($seconds > 3600){
        $hours = intval($seconds/3600);
        $minutes = $seconds % 3600;
        $time = $hours.":".gmstrftime('%M:%S', $minutes);
    }else{
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}

function get_effective_time($uid, $data_id, $data_type){
	$CI =& get_instance();
	$time = time();
	$sql = "SELECT * FROM {$CI->db->dbprefix}o2o_student_item_terms WHERE data_type='{$data_type}' AND data_id = '{$data_id}' AND uid = '{$uid}'";
	$result = $CI->db->query($sql)->row_array();
	if(!$result){
		return 0;
	}else{
		if($result['lose_time'] > $time){
			$day = ceil(($result['lose_time'] - $time) / (3600 * 24));
		}else{
			$day = 0;
		}
		return $day;
	}
}

function check_effective_time($uid, $data_id, $data_type){
	$CI =& get_instance();
	$time = time();
	$sql = "SELECT * FROM {$CI->db->dbprefix}o2o_student_item_terms WHERE data_type='{$data_type}' AND data_id = '{$data_id}' AND uid = '{$uid}'";
	$result = $CI->db->query($sql)->row_array();
	if(!$result){
		return false;
	}else{
		if($result['lose_time'] > $time || $data_type == 2){
			return true;
		}else{
			return false;
		}
	}
}

function check_user_learn_card($uid, $id, $type){
	$CI =& get_instance();
	$today_time = strtotime(date('Y-m-d',time()));
	$sql = "SELECT item.*, card.title, s_card.id AS sid from {$CI->db->dbprefix}o2o_school_learn_card_item AS item ";
	$sql .= "LEFT JOIN {$CI->db->dbprefix}o2o_school_learn_card AS card ON(card.id = item.card_id) ";
	$sql .= "LEFT JOIN {$CI->db->dbprefix}o2o_school_student_learn_card AS s_card ON(s_card.card_id=item.card_id) ";
	$sql .= " WHERE item.content_id='{$id}' AND item.content_type='{$type}' AND s_card.user_id = '{$uid}' AND s_card.end_time > '{$today_time}' GROUP BY item.card_id";
	$result = $CI->db->query($sql)->row_array();
	return $result;
}

function get_vip_endtime($uid){
	$CI =& get_instance();
	$sql = "SELECT vip_expire_day FROM {$CI->db->dbprefix}user WHERE id = $uid";
	$result = $CI->db->query($sql)->row_array();
	return $result['vip_expire_day'];
}

function getip() {
	if (isset ( $_SERVER )) {
		if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
			$aIps = explode ( ',', $_SERVER ['HTTP_X_FORWARDED_FOR'] );
			foreach ( $aIps as $sIp ) {
				$sIp = trim ( $sIp );
				if ($sIp != 'unknown') {
					$sRealIp = $sIp;
					break;
				}
			}
		} elseif (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) {
			$sRealIp = $_SERVER ['HTTP_CLIENT_IP'];
		} else {
			if (isset ( $_SERVER ['REMOTE_ADDR'] )) {
				$sRealIp = $_SERVER ['REMOTE_ADDR'];
			} else {
				$sRealIp = '0.0.0.0';
			}
		}
	} else {
		if (getenv ( 'HTTP_X_FORWARDED_FOR' )) {
			$sRealIp = getenv ( 'HTTP_X_FORWARDED_FOR' );
		} elseif (getenv ( 'HTTP_CLIENT_IP' )) {
			$sRealIp = getenv ( 'HTTP_CLIENT_IP' );
		} else {
			$sRealIp = getenv ( 'REMOTE_ADDR' );
		}
	}
	return $sRealIp;
}

function cut_str($sourcestr,$cutlength)
{
	$returnstr='';
	$i=0;
	$n=0;
	$str_length=strlen($sourcestr);//字符串的字节数
	while (($n<$cutlength) and ($i<=$str_length))
	{
		$temp_str=substr($sourcestr,$i,1);
		$ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
		if ($ascnum>=224)    //如果ASCII位高与224，
		{
			$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符        
			$i=$i+3;            //实际Byte计为3
			$n++;            //字串长度计1
		}
		elseif ($ascnum>=192) //如果ASCII位高与192，
		{
			$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i=$i+2;            //实际Byte计为2
			$n++;            //字串长度计1
		}
		elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
		{
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1;            //实际的Byte数仍计1个
			$n++;            //但考虑整体美观，大写字母计成一个高位字符
		}
		else                //其他情况下，包括小写字母和半角标点符号，
		{
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1;            //实际的Byte数计1个
			$n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
		}
	}
	if ($str_length>$cutlength){
		$returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
	}
	return $returnstr;
}
?>